﻿using CWCS.Common;
using CWCS.DataAccess;
using CWCS.Entity;
using CWCS.Entity.SRM;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;
using System.Linq;
using System.Text;
using System.Configuration;
using CWCS.Core.Library.PLCManager;
using System.Collections;
using System.Threading;
using CWCS.Entity.Convery;
using CWCS.DataAccess.DataProvider;
using CWCS.Core.Library.ModbusManager;
using CWCS.BLL.NTIScModbus;
using CWCS.Core.Library.ScanManager;
using System.Collections.Concurrent;
using CWCS.Core.Library.SmartPLCManager;

namespace CWCS.BLL
{
    public abstract class BLLBase
    {
        public string WareHouseID = "";
        public string ZoneCode = "";
        public string AreaCode = "";        
        public static string FaceCode = "";
        public static string[] TrayMode;
        public static int ActivieTime;
        public static int Mode = 0;
        public static string modeName = "";
        public static DateTime modeTime = DateTime.Now;
        public static int ActivieModeime;        
        public string LineCode = "";
        public string DTSIP = "";
        public string LEDIP = "";
        public string userpswd = "";
        public string MESStatus = "1";
        public int celllen = 30;//默认为电控最长长度
        public string cellbarcodetype = "";
        public string barcodeCheck = "";
        public string WaitCount = "";
        public string WaitCountMin = "";
        public static string user;//当前用户
        public static bool loginFlag = false;//当前用户登录状态
        public static DateTime loginTime=DateTime.Now ;//当前用户登录成功时间
        public Dictionary<string, string> DNextSta = new Dictionary<string, string>();
        public Dictionary<string, int> DSCInfoCount = new Dictionary<string, int>();

        public static ConcurrentDictionary<string, TcpClientInfo> _tcpClientInfo = new ConcurrentDictionary<string, TcpClientInfo>(); //
        public static List<ReadConfigInfo> _readConfigInfo = new List<ReadConfigInfo>(); //

        public static CRCTask crc = new CRCTask();//堆垛机任务类
        public static PhotoBLL photoBLL = new PhotoBLL();
        public static ModbusCRCTask modbuscrc = new ModbusCRCTask();//堆垛机任务类

        public static List<CRCStatus> list_srm_info = new List<CRCStatus>();//堆垛机状态类
        public static List<CRCObject> list_srm_object = new List<CRCObject>();//堆垛机实体类
        public static List<ConveryZoneInfo> converyZoneInfo = new List<ConveryZoneInfo>();//输送机站台信息表
        public static List<AdjustLocation> adjustLocationInfo = new List<AdjustLocation>();//工装站台信息表
        public Dictionary<string, string> scStatus = new Dictionary<string, string>();
        public static bool ocvMsaStatus = false;
        public static Dictionary<string, string> ocvMsa = new Dictionary<string, string>();
        public static Dictionary<string, SCTaskMode> modeFlag = new Dictionary<string, SCTaskMode>();
        public static Thread TaskThread;
        public static Thread TaskThread1;
        //状态
        public static string EQUIPMENT_ERROR = "Equipment_Error";
        public static string EQUIPMENT_OK = "Equipment_OK";
        public static string CR_POS_GET_EXECUTED = "25";//取货前行走完成
        public static string CR_GETC_WAIT_H = "112";//准备取货
        public static string CR_GETC_POS_RUNNING = "113";//取货前的移动
        public static string CR_GETC_GET_RUNNING = "114";//开始取货
        public static string CR_GETC_EXECUTED = "121";//取货完成
        public static string CR_PUTC_WAIT_H = "128";//准备放货
        public static string CR_PUTC_POS_RUNNING = "129";//放货前的移动
        public static string CR_PUTC_PUT_RUNNING = "130";//开始放货
        public static string CR_PUTC_EXECUTED = "137";//放货完成
        public List<ConveryEntity> lst;
        public List<SmartEntity> smartLst;


        public static int CR_NO_FUNC = 0;//清除
        public static int CR_POS_GET = 16;//取货前行走
        public static int CR_GETC = 112;//取货指令
        public static int CR_PUTC = 128;//放货指令
        //今天国际堆垛机报头
        public static byte[] MessageHeader_NTI_4000 = new byte[] { 0xFF };
        public static byte[] MessageHeader_NTI_6000 = new byte[] { 0xFF };
        public static byte[] MessageHeader_NTI_2000 = new byte[] { 0xFF };

        //public ConveryModbus plc;
        public ConveryPLC plc;
        public SmartPLC smartPlc;
        public static Hashtable AlarmHash = Hashtable.Synchronized(new Hashtable());//堆垛机详细报警信息存储
        public static List<SRM_Status_Entity> L_SRMStatus = new List<SRM_Status_Entity>();//堆垛机状态类
        public DALDATA dal = new DALDATA();
        protected BLLBase()
        {

            WareHouseID = ConfigurationManager.AppSettings["WarehouseID"].ToString().Trim();
            ZoneCode = ConfigurationManager.AppSettings["ZoneCode"].ToString().Trim();
            AreaCode = ConfigurationManager.AppSettings["AreaCode"].ToString().Trim();
            LineCode = ConfigurationManager.AppSettings["LineCode"].ToString().Trim();
            barcodeCheck = ConfigurationManager.AppSettings["BarcodeCheck"].ToString().Trim();
            WaitCount = ConfigurationManager.AppSettings["WaitCount"].ToString().Trim();
            WaitCountMin = ConfigurationManager.AppSettings["WaitCountMin"].ToString().Trim();
            FaceCode = ConfigurationManager.AppSettings["FaceCode"].ToString().Trim();
            TrayMode = ConfigurationManager.AppSettings["TrayMode"].ToString().Trim().Split(new char[] { ';' });
            ActivieTime = int.Parse(ConfigurationManager.AppSettings["ActivieTime"].ToString().Trim());
            ActivieModeime = int.Parse(ConfigurationManager.AppSettings["ActivieModeime"].ToString().Trim());            
        }
        public bool GetLedSendInfo(string zoneid, ref int result, ref string msg)
        {
            msg = "";
            result = 0;
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_zoneid",MySqlDbType.VarChar,200),
                new MySqlParameter(@"o_result",MySqlDbType.Int32),
                new MySqlParameter(@"o_msg",MySqlDbType.VarChar,1500)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = zoneid;
            parms[1].Direction = ParameterDirection.Output;
            parms[1].Value = result;
            parms[2].Direction = ParameterDirection.Output;
            parms[2].Value = msg;
            int i = DataAccessFactory.Instance.ExecuteNonQuery("m_getledsendinfo",CommandType.StoredProcedure,parms);
            if (System.String.IsNullOrEmpty(parms[1].Value.ToString()) || parms[1].Value.ToString() == "0")
            {
                result = 0;
                msg = parms[2].Value.ToString();
                return false;
            }
            else
            {
                result = 1;
                msg = parms[2].Value.ToString();
                return true;
            }

        }
        public bool GettaskInfo(string WareHouseID, string i_BarCode,string i_BarCode2, string i_stationnum, string i_stationtype, string i_goodstype, string i_ZoneCode, string i_taskno, string i_checkflag, string i_itemcode, ref string msg ,ref int result )
        {
            msg = "";
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_warehouseid", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_barcode", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_barcode2", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_stationnum", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_stationtype", MySqlDbType.VarChar, 10),
                new MySqlParameter(@"i_goodstype", MySqlDbType.Int32,10),
                new MySqlParameter(@"i_ZoneCode", MySqlDbType.VarChar, 10),
                new MySqlParameter(@"i_taskno", MySqlDbType.Int32),
                new MySqlParameter(@"i_checkflag", MySqlDbType.Int32),
                new MySqlParameter(@"i_itemcode", MySqlDbType.VarChar,32),
                new MySqlParameter(@"o_result", MySqlDbType.Int32),
                new MySqlParameter(@"o_msg", MySqlDbType.VarChar,200)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = string.IsNullOrEmpty(i_BarCode.Trim(' ')) ? null : i_BarCode.Trim(' ').Length < 5 ? null : i_BarCode;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = string.IsNullOrEmpty(i_BarCode2.Trim(' ')) ? null : i_BarCode2.Trim(' ').Length < 5 ? null : i_BarCode2;
            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = i_stationnum;  
            parms[4].Direction = ParameterDirection.Input;
            parms[4].Value = i_stationtype;
            parms[5].Direction = ParameterDirection.Input;
            parms[5].Value = i_goodstype;
            parms[6].Direction = ParameterDirection.Input;
            parms[6].Value = i_ZoneCode;
            parms[7].Direction = ParameterDirection.Input;
            parms[7].Value = i_taskno;
            parms[8].Direction = ParameterDirection.Input;
            parms[8].Value = i_checkflag;
            parms[9].Direction = ParameterDirection.Input;
            parms[9].Value = i_itemcode;
            parms[10].Direction = ParameterDirection.Output;
            parms[10].Value = 0;
            parms[11].Direction = ParameterDirection.Output;
            parms[11].Value = "";
            int i = DataAccessFactory.Instance.ExecuteNonQuery("cwcs_gettaskinfo_hc", CommandType.StoredProcedure, parms);
            if (System.String.IsNullOrEmpty(parms[10].Value.ToString()) || parms[10].Value.ToString() == "0")
            {
                result = 0;
                msg = parms[11].Value.ToString();
                return false;
            }
            else
            {
                result = int.Parse(parms[10].Value.ToString());
                msg = parms[11].Value.ToString();
                return true;
            }
        }

        public bool changTostation(string WareHouseID, string scno, string taskno, int colum, ref string tostation)
        {
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_warehouseid", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_taskno", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_equipmentnumber", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_columblock", MySqlDbType.Int32),
                new MySqlParameter(@"o_result", MySqlDbType.Int32),
                new MySqlParameter(@"o_tostation", MySqlDbType.VarChar,50)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = taskno;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = scno;
            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = colum;
            parms[4].Direction = ParameterDirection.Output;
            parms[4].Value = 0;
            parms[5].Direction = ParameterDirection.Output;
            parms[5].Value = "";
            int i = DataAccessFactory.Instance.ExecuteNonQuery("cwcs_changeinboundloc", CommandType.StoredProcedure, parms);
            if (parms[4].Value.ToString() == "1")
            {
                tostation = parms[5].Value.ToString();
                return true;
            }
            return false;
        }

        protected bool UpdateSCStatus(string WareHouseID, string SCNO, string status)
        {
            string oldstatus = "";
            if (!string.IsNullOrEmpty(status))
            {
                if (status == "Equipment_OK")
                {
                    oldstatus = "Equipment_Error";
                }
                else
                {
                    oldstatus = "Equipment_OK";
                }
                string Sql_UpdateSCStatus = @"INSERT INTO equipment SELECT *  FROM equipment a WHERE statecode = '" + oldstatus + "' AND equipmentnumber = '" + SCNO + "' ON DUPLICATE KEY UPDATE statecode =  '" + status + "';";
                int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, Sql_UpdateSCStatus, null);
                return i > 0;
            }
            return false;
        }

        protected bool UpdateSCDoorInfo(string SCNO, string note)
        {
            string Sql_UpdateSCStatus = @" UPDATE equipment set note='" + note + "'where equipmentnumber ='" + SCNO + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, Sql_UpdateSCStatus, null);
            return i > 0;
        }

        /// <summary>
        /// 货叉1获取任务后，更新输送机站台地址
        /// </summary>
        /// <param name="WareHouseID"></param>
        /// <param name="TaskNo"></param>
        /// <param name="BarCode"></param>
        /// <param name="TaskType"></param>
        /// <param name="TaskStatus"></param>
        /// <param name="RunStatus"></param>
        /// <returns></returns>
        protected bool UpdateTaskStation(string i_barcode, string i_taskno, string i_tostation, string i_updatetostation)
        {
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_barcode", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_taskno", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_tostation", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_updatetostation", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"o_result", MySqlDbType.Int32)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = string.IsNullOrEmpty(i_barcode) ? "0000000000" : i_barcode;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = i_taskno;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = i_tostation;
            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = i_updatetostation;
            parms[4].Direction = ParameterDirection.Output;
            parms[4].Value = 0;
            int i = DataAccessFactory.Instance.ExecuteNonQuery("cwcs_updatetaskstation_p", CommandType.StoredProcedure, parms);
            if (System.String.IsNullOrEmpty(parms[4].Value.ToString()) || parms[4].Value.ToString() == "0")
            {
                return false;
            }
            return true;
        }
        protected bool UpdateTaskStatus(string fromstation, string WareHouseID, string TaskNo, string BarCode, string TaskType, string TaskStatus, string RunStatus)
        {
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_warehouseid", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_fromstation", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_barcode", MySqlDbType.VarChar, 20),
                new MySqlParameter(@"i_taskno", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"i_equipmenttype", MySqlDbType.VarChar, 10), 
                new MySqlParameter(@"i_taskstatus", MySqlDbType.VarChar),
                new MySqlParameter(@"i_runstatus", MySqlDbType.VarChar, 10),
                new MySqlParameter(@"i_parentlognoid", MySqlDbType.VarChar, 50),
                new MySqlParameter(@"o_result", MySqlDbType.Int32)
            };
       
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = fromstation;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = string.IsNullOrEmpty(BarCode)?"0000000000":BarCode;
            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = TaskNo;
            parms[4].Direction = ParameterDirection.Input;
            parms[4].Value = TaskType;
            parms[5].Direction = ParameterDirection.Input;
            parms[5].Value = TaskStatus;
            parms[6].Direction = ParameterDirection.Input;
            parms[6].Value = RunStatus;
            parms[7].Direction = ParameterDirection.Input;
            parms[7].Value = "";
            parms[8].Direction = ParameterDirection.Output;
            parms[8].Value = 0;
            int i =  DataAccessFactory.Instance.ExecuteNonQuery("CWCS_UPDATETASKSTATUS_P", CommandType.StoredProcedure, parms);
            if (System.String.IsNullOrEmpty(parms[8].Value.ToString()) || parms[8].Value.ToString() == "0")
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取WCS任务
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="taskstatus"></param>
        /// <param name="fromtime"></param>
        /// <param name="totime"></param>
        /// <param name="wmstaskno"></param>
        /// <param name="taskno"></param>
        /// <param name="fromstation"></param>
        /// <param name="tostation"></param>
        /// <param name="barcode"></param>
        /// <param name="zoneid"></param>
        /// <returns></returns>
        protected DataTable GetWCS_TaskInfo(int tasktype, int taskstatus, string fromtime, string totime, string wmstaskno, string taskno, string fromstation, string tostation, string barcode,string zoneid)
        {

            DataSet ds = null;
            string equipmenttype = string.Empty;
            if (tasktype == 1)
                equipmenttype = "STA";
            else if (tasktype == 2)
                equipmenttype = "SC";
            else if (tasktype == 3)
                equipmenttype = "AGV";
            string zonecode = ZoneCode == "HC" ? "'A','B','C'" : "'D','E'";

            if (tasktype == 0)
            {
                if (taskstatus == 0)
                {
                    ds = DataAccessFactory.Instance.ExecuteDataSet("select * from view_wcstaskinfo where wmstaskno like '%" + wmstaskno + "%' and taskno like '%" + taskno + "%'  and fromstation like '%" + fromstation + "%' and tostation like '%" + tostation + "%'  and barcode like'%" + barcode + "%' and zone in(" + zonecode + ") ", CommandType.Text, null);
                }
                else
                {
                    ds = DataAccessFactory.Instance.ExecuteDataSet("select * from view_wcstaskinfo_history where createtime between date_format('" + fromtime + "','%Y-%m-%d %H:%i:%s') and date_format('" + totime + "','%Y-%m-%d %H:%i:%s') and wmstaskno like '%" + wmstaskno + "%'  and taskno like '%" + taskno + "%' and fromstation = '%" + fromstation + "%' and tostation like '%" + tostation + "%' and barcode like'%" + barcode + "%'  and zone in(" + zonecode + ") ", CommandType.Text, null);
                }
            }
            else if (tasktype == 3)
            {
                ds = DataAccessFactory.Instance.ExecuteDataSet("select * from view_dualtask ", CommandType.Text, null);
            }
            else
            {
                if (taskstatus == 0)
                {
                    ds = DataAccessFactory.Instance.ExecuteDataSet("select * from view_wcs_subtaskinfo where createtime between date_format('" + fromtime + "','%Y-%m-%d %H:%i:%s') and date_format('" + totime + "','%Y-%m-%d %H:%i:%s') and wmstaskno like '%" + wmstaskno + "%' and equipmenttype = '" + equipmenttype + "' and   taskno like '%" + taskno + "%' and fromstation like '%" + fromstation + "%'and tostation like '%" + tostation + "%' and barcode like '%" + barcode + "%'  and zone in(" + zonecode + ")", CommandType.Text, null);
                }
                else if (taskstatus == 2)
                {
                    ds = DataAccessFactory.Instance.ExecuteDataSet("select * from view_wcs_subtaskinfo where createtime between date_format('" + fromtime + "','%Y-%m-%d %H:%i:%s') and date_format('" + totime + "','%Y-%m-%d %H:%i:%s') and wmstaskno like '%" + wmstaskno + "%' and taskno like '%" + taskno + "%' and fromstation like '%" + fromstation + "%' and tostation like '%" + tostation + "%' and  barcode like '%" + barcode + "%'and equipmenttype = '" + equipmenttype + "'  and taskstatus in ('" + taskstatus + "') and zone in(" + zonecode + ") ", CommandType.Text, null);
                }
                else if (taskstatus == 1)
                {

                    if (wmstaskno == "" && taskno == "" && fromstation == "" && tostation == "" && barcode == "")
                    {
                        ds = DataAccessFactory.Instance.ExecuteDataSet("select * from(select * from view_wcs_subtaskinfohistory where createtime between date_format('" + fromtime + "','%Y-%m-%d %H:%i:%s') and date_format('" + totime + "','%Y-%m-%d %H:%i:%s') and equipmenttype = '" + equipmenttype + "'  and zone in(" + zonecode + ") limit 40) t", CommandType.Text, null);
                    }
                    else
                    {
                        string sql = "and 1=1 ";
                        if (wmstaskno != "")
                        {
                            sql = sql + "and wmstaskno='" + wmstaskno + "'";
                        }
                        if (taskno != "")
                        {
                            sql = sql + "and taskno='" + taskno + "'";
                        }
                        if (fromstation != "")
                        {
                            sql = sql + "and fromstation='" + fromstation + "'";
                        }
                        if (tostation != "")
                        {
                            sql = sql + "and tostation='" + tostation + "'";
                        }
                        if (barcode != "")
                        {
                            sql = sql +"and barcode='" + barcode + "'";
                        }
                        ds = DataAccessFactory.Instance.ExecuteDataSet("select * from(select * from view_wcs_subtaskinfohistory where createtime between date_format('" + fromtime + "','%Y-%m-%d %H:%i:%s') and date_format('" + totime + "','%Y-%m-%d %H:%i:%s')" + sql + ") t", CommandType.Text, null);
                    }
                }
            }
            DataTable dt = null;
            if (ds == null || ds.Tables.Count == 0)
            {
                return null;
            }
            else
            {
                if (ds.Tables[0].Rows.Count > 0)
                {

                    DataRow[] drs = ds.Tables[0].Select("1=1", "createtime desc");
                    var quey = from v in drs.AsEnumerable() where zonecode.Replace("'", "").Split(',').ToArray().Contains(v.Field<string>("zone").ToString().Trim()) select v;
                    if (quey.Count() > 0)
                        dt = quey.CopyToDataTable();
                    else
                    {
                        dt = ds.Tables[0];
                        dt.Rows.Clear();
                    }
                }
                else
                    dt = ds.Tables[0];
            }
            return dt;
        }



        protected DataTable GetZoneCode()
        {

            string sql = "select code,name from zone ";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            DataTable dt = null;
            if (ds == null || ds.Tables.Count==0)
            {
                return null;
            }
            else
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string zonecode = ZoneCode == "HC" ? "'B','C'" : "'E'";
                    if (ds.Tables[0].Select("code in(" + zonecode + ")").Count() > 0)
                    {
                        DataRow[] drs = ds.Tables[0].Select("code in(" + zonecode + ")", "code desc");
                        var quey = from v in drs.AsEnumerable() where zonecode.Replace("'", "").Split(',').ToArray().Contains(v.Field<string>("code").ToString().Trim()) select v;
                        if (quey.Count() > 0)
                            dt = quey.CopyToDataTable();
                        else
                        {
                            dt = ds.Tables[0];
                            dt.Rows.Clear();
                        }
                    }
                    else
                    {
                        dt = ds.Tables[0];
                        dt.Rows.Clear();
                    }
                }
                else
                    dt = ds.Tables[0];
            }
            return dt;
        }
        public bool CheckExistsTask(string tostation,ref string taskno)
        {
            string sql = @"select count(1),a.taskno from (select taskno from wcs_subtaskinfo ws where ws.equipmenttype='SC' and ws.taskno in" +
                "(select taskno from wcs_subtaskinfo ws where tostation='" + tostation + "') and ws.runstatus='0' and ws.field2='Task_OutBound' order by ws.createtime limit 1) a";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds.Tables[0].Rows[0][0].ToString().Trim()=="0")
            {
                return false;
            }
            else
            {
                taskno = ds.Tables[0].Rows[0][1].ToString().Trim();
                return  true;
            }
        }

        /// <summary>
        /// 查询WCS任务
        /// </summary>
        /// <param name="tostation"></param>
        /// <param name="technologyCode"></param>
        /// <param name="taskno"></param>
        /// <returns></returns>
        public int CheckExistsTask(string tostation,string tostation1)
        {
            int count = 0;
            // string sql = @"SELECT COUNT(1) FROM (SELECT ws.taskno FROM wcs_subtaskinfo ws WHERE ws.equipmenttype= 'STA' AND ws.tostation = '"+tostation+"') a";
            string sql = @"SELECT COUNT(1) FROM (SELECT ws.taskno FROM wcs_subtaskinfo ws WHERE ws.equipmenttype= 'STA' AND ws.tostation = '" + tostation + "' UNION SELECT a.taskno FROM (SELECT ws.taskno FROM wcs_subtaskinfo ws WHERE ws.runstatus= '1' AND ws.equipmenttype= 'SC' AND ws.field1 IN(SELECT t.tasknumber FROM task t LEFT JOIN technology t1 ON t.version = t1.technologyid WHERE t.tasktypecode = 'Task_OutBound' AND t.targetaddresstext= '"+tostation1+"' AND t1.code= 'P'))a) AA";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = int.Parse(ds.Tables[0].Rows[0][0].ToString().Trim());
                return count;
            }
            else
            {
                return 0;
            }
        }
        public bool CheckExistsTask(string tostation, string technologyCode, ref string taskno)
        {
            string sql = @"SELECT COUNT(1),a.taskno FROM (SELECT ws.taskno FROM wcs_subtaskinfo ws WHERE ws.runstatus= '0' AND ws.equipmenttype= 'SC' AND ws.field1 IN" +
                "(SELECT t.tasknumber FROM task t LEFT JOIN technology t1 ON t.version = t1.technologyid WHERE t.tasktypecode = 'Task_OutBound' AND t.targetaddresstext= '" + tostation + "' AND t1.code= '" + technologyCode + "')  ORDER BY ws.createtime LIMIT 1) a";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds.Tables[0].Rows[0][0].ToString().Trim() == "0")
            {
                return false;
            }
            else
            {
                taskno = ds.Tables[0].Rows[0][1].ToString().Trim();
                return true;
            }
        }

        public int GetCellExecteCount(string station)
        {
            string sql = @"select cellcountexcting from wcs_cellcount wc   WHERE wc.FINIASTATION='" + station + "'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            int taskCount = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            return taskCount;
        }
        public bool CheckExistsWCS_SubTask(string tostation, ref string taskno)
        {
            string sql = @"select count(1),a.taskno from (select taskno from wcs_subtaskinfo ws where ws.taskno in" +
                "(select taskno from wcs_subtaskinfo ws where tostation='" + tostation + "')  order by ws.createtime limit 1) a";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds.Tables[0].Rows[0][0].ToString().Trim() == "0")
            {
                return false;
            }
            else
            {
                taskno = ds.Tables[0].Rows[0][1].ToString().Trim();
                return true;
            }
        }
        public bool UpdateTaskRunstatus(string taskno)
        {
            string sql = "update wcs_subtaskinfo ws set ws.runstatus='1' where ws.equipmenttype='SC'" +
                "and ws.taskno ='"+ taskno + "' and ws.runstatus='0' ";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }
        /// <summary>
        /// 插入智能电表具体数据
        /// </summary>
        /// <param name="zone"></param>
        /// <param name="equipmentnumber"></param>
        /// <param name="equipmenttype"></param>
        /// <param name="equipmentIP"></param>
        /// <param name="CombinedActivePower"></param>
        /// <param name="TotalPositiveActivePower"></param>
        /// <param name="machineid"></param>
        /// <param name="equipmentname"></param>
        /// <param name="msg"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public bool InsertSmartElectricData(string zone, string equipmentnumber, string equipmenttype, string equipmentIP, double CombinedActivePower, double TotalPositiveActivePower, string machineid, string equipmentname, ref string msg, ref int result)
        {
            msg = "";
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter(@"i_zonecode", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_equipmentnumber", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_equipmenttype", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_equipmentIP", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_CombinedActivePower", MySqlDbType.Decimal, 20),
                new MySqlParameter(@"i_TotalPositiveActivePower", MySqlDbType.Decimal, 20),
                new MySqlParameter(@"i_machineid", MySqlDbType.VarChar, 32),
                new MySqlParameter(@"i_equipmentname", MySqlDbType.VarChar, 64),
                new MySqlParameter(@"o_result", MySqlDbType.Int32),
                new MySqlParameter(@"o_msg", MySqlDbType.VarChar,200)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = zone;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = equipmentnumber;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = equipmenttype;
            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = equipmentIP;
            parms[4].Direction = ParameterDirection.Input;
            parms[4].Value = CombinedActivePower;
            parms[5].Direction = ParameterDirection.Input;
            parms[5].Value = TotalPositiveActivePower;
            parms[6].Direction = ParameterDirection.Input;
            parms[6].Value = machineid;
            parms[7].Direction = ParameterDirection.Input;
            parms[7].Value = equipmentname;
            parms[8].Direction = ParameterDirection.Output;
            parms[8].Value = 0;
            parms[9].Direction = ParameterDirection.Output;
            parms[9].Value = "";
            int i = DataAccessFactory.Instance.ExecuteNonQuery("Pro_InsertElectricData", CommandType.StoredProcedure, parms);
            if (System.String.IsNullOrEmpty(parms[8].Value.ToString()) || parms[8].Value.ToString() == "0")
            {
                result = 0;
                msg = parms[9].Value.ToString();
                return false;
            }
            else
            {
                result = int.Parse(parms[8].Value.ToString());
                msg = parms[9].Value.ToString();
                return true;
            }
        }
        /// <summary>
        /// 判断是否存在分容库位，若存在分容库位，传出库位数与堆垛机设备号
        /// </summary>
        /// <returns></returns>
        public int ExistsFREmptyLocation(ref string equipmentnumber)
        {
            string sql = @"SELECT COUNT(1) AS count,e.equipmentnumber FROM location l LEFT JOIN equipment e ON l.per_equipmentid = e.equipmentid WHERE l.zoneid ='911e2d4b5b154247c648b48e03c51c16'"+ 
    " AND l.locationflag ='LocationFlag_Enabled' AND l.locationstate ='LocationState_Empty' AND e.statecode ='Equipment_OK' GROUP BY e.equipmentnumber HAVING count>0 ORDER BY count DESC LIMIT 1";
            int result = 0;
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            result =Int32.Parse(ds.Tables[0].Rows[0][0].ToString().Trim());
            if (ds.Tables[0].Rows[0][0].ToString().Trim() == "0")
            {
                return 0;
            }
            else
            {
                equipmentnumber = ds.Tables[0].Rows[0][1].ToString().Trim();
                return result;
            }
        }

        /// <summary>
        /// 判断分容缓存库位是否有料，若有料，则更新缓存位库位标记
        /// </summary>
        /// <returns></returns>
        public int ExistsBufferLocation(string equipmentnumber)
        {
            string sql = @"SELECT COUNT(1) AS count FROM location l LEFT JOIN equipment e ON l.per_equipmentid = e.equipmentid WHERE l.zoneid ='1069612248a4913e68b246ac6e3d05b4'" +
    " AND  l.locationstate ='LocationState_Stored' AND l.outflag !='M1'  AND e.statecode ='Equipment_OK' AND e.equipmentnumber='"+ equipmentnumber + "' ORDER BY count DESC ";
            int result = 0;
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            result = Int32.Parse(ds.Tables[0].Rows[0][0].ToString().Trim());
            if (ds.Tables[0].Rows[0][0].ToString().Trim() == "0")
            {
                return 0;
            }
            else
            {
                return result;
            }
        }
        public bool UpdateBufferLocationOutflag(string equipmentnumber,int buffer_count)
        {
            string sql = "UPDATE location l LEFT JOIN equipment e ON l.per_equipmentid = e.equipmentid  SET l.outflag ='M1' WHERE l.zoneid='1069612248a4913e68b246ac6e3d05b4' AND   l.locationstate ='LocationState_Stored' and (containerid is not null and containerid !='') AND l.outflag !='M1'  AND e.statecode ='Equipment_OK' AND e.equipmentnumber='" + equipmentnumber + "' ";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }


        #region 机械手
        protected string CheckExistsCell(ref bool flag, ref string strid, ref string message, string zoneid, string containerbarcode, string jk_name, string sfc_code)
        {
            flag = false;
            strid = "";
            message = "";
            string sql = @"select distinct result,id,message from jk_mes where  jk_name = '" + jk_name + "'and sfc_code = '" + sfc_code + "' ";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return "11";
            }
            else
            {
                flag = true;
                strid = ds.Tables[0].Rows[0][1].ToString().Trim();
                message = ds.Tables[0].Rows[0][2].ToString().Trim();
                return ds.Tables[0].Rows[0][0].ToString().Trim();
            }
        }
        /// <summary>
        /// 查询托盘接口是否存在，机械手业务
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="strid"></param>
        /// <param name="message"></param>
        /// <param name="zoneid"></param>
        /// <param name="containerbarcode"></param>
        /// <param name="jk_name"></param>
        /// <param name="sfc_code"></param>
        /// <returns></returns>
        protected string CheckExistsBarCode(ref bool flag, ref string strid, ref string message, string zoneid,  string jk_name, string containerbarcode)
        {
            flag = false;
            strid = "";
            message = "";
            string sql = @"select distinct result,id,message from jk_mes where  jk_name = '" + jk_name + "'and containerbarcode = '" + containerbarcode + "' ";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return "11";
            }
            else
            {
                flag = true;
                strid = ds.Tables[0].Rows[0][1].ToString().Trim();
                message = ds.Tables[0].Rows[0][2].ToString().Trim();
                return ds.Tables[0].Rows[0][0].ToString().Trim();
            }
        }

        protected bool CheckBindResult(string containerbarcode, string jk_name)
        {
            string sql = @"select count(1) from jk_mes where  jk_name = '" + jk_name + "'and containerbarcode = '" + containerbarcode + "' and result=''";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0 || ds.Tables[0].Rows[0][0].ToString()=="0")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        protected int getCountByBarcode(string containerbarcode)
        {
            string sql = @"select count(1) from wcs_itemcode  wi where  wi.barcode = '" + containerbarcode + "' and SUBSTR(wi.itemcode,1,3)!='WCS' and wi.itemcode is not null and wi.itemcode!='Empty'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return 0;
            }
            else
            {
                return int.Parse(ds.Tables[0].Rows[0][0].ToString());
            }
        }
        protected bool CheckCellType(string equipmentnumber)
        {
            string sql = @"select celllen,celltype,messtatus from barcodetype  where itemid in (select itemid from equipment where typecode='Equipment_Robot' and equipmentnumber='" + equipmentnumber + "')";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                celllen = 0;
                return false;
            }
            else
            {
                
                celllen = int.Parse(ds.Tables[0].Rows[0][0].ToString().Trim());
                cellbarcodetype  = ds.Tables[0].Rows[0][1].ToString().Trim();
                MESStatus = ds.Tables[0].Rows[0][2].ToString().Trim();
                return true;
            }
        }
        public int checkExists(string barcode)
        {
            int result = -1;
            string sql = @"select sum(qty)" +
               " from (select count(1) as qty" +
          " from wcs_itemcode where itemcode = '" + barcode + "' union all select count(1) as qty from itemdetail where itembarcode = '" + barcode + "'" +
          "UNION ALL SELECT COUNT(1) AS qty FROM jk_mes jm WHERE jm.sfc_code =  '" + barcode + "' AND jm.jk_name = 'bindSFCintoTray')as t";
            object ob = DataAccessFactory.Instance.ExecuteScalar(CommandType.Text, sql, null);
            if (ob != null)
                return int.Parse(ob.ToString());

            return result;
        }
        public int CheckTrayGradeLevelCount(string barcode,ref string level)
        {
            int result = -1;
            string sql = @"SELECT COUNT(DISTINCT ig.gradegroup),ig.gradegroup FROM itemdetail_grade ig WHERE ig.containerbarcode ='" + barcode+"'";
            //object ob = DataAccessFactory.Instance.ExecuteScalar(CommandType.Text, sql, null);
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null)
            {
                level = ds.Tables[0].Rows[0][1].ToString();
                return int.Parse(ds.Tables[0].Rows[0][0].ToString());
            }
            return result;
        }
        public bool DeleteItemdetail_Grade(string containerbarcode)
        {
            if (string.IsNullOrEmpty(containerbarcode))
                containerbarcode = "EMPTY";
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("I_BARCODE", MySqlDbType.VarChar, 32),
                new MySqlParameter("o_result", MySqlDbType.Int32),
                new MySqlParameter("O_MSG",MySqlDbType.VarChar,100)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = containerbarcode;

            parms[1].Direction = ParameterDirection.Output;
            parms[1].Value = 0;
            parms[2].Direction = ParameterDirection.Output;
            parms[2].Value = "";

            int i = DataAccessFactory.Instance.ExecuteNonQuery("CWCS_MOVEITEMDETAIL_GRADE", CommandType.StoredProcedure, parms);
            if (!System.String.IsNullOrEmpty(parms[1].Value.ToString()))
            {
                if (parms[1].Value == null)
                    return false;
                else
                    return int.Parse(parms[1].Value.ToString()) > 0;
            }
            else
                return false;
        }

        public string wcs_getpswd(string username)
        {
            string strSql = "select userpswd from LMEP_SYSTEM_USER t where userid='" + username + "'";
            string cellqty = string.Empty;
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(strSql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count == 0)
            {
                return "";
            }
            else
            {
                cellqty = ds.Tables[0].Rows[0][0].ToString();
                return cellqty;
            }
        }
        public int CheckLocationState(string locationnumber)
        {
            string[] strResult = new string[3] { "0", "", "" };
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("i_warehouseId", MySqlDbType.VarChar, 32),
                new MySqlParameter("i_LocationNumber", MySqlDbType.VarChar, 20),
                new MySqlParameter("o_ifsucceed", MySqlDbType.Int32)
            };

            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = locationnumber.ToString().Trim();

            parms[2].Direction = ParameterDirection.Output;
            parms[2].Value = 0;
            int i = DataAccessFactory.Instance.ExecuteNonQuery("WCS_CHECKLOCATION_ATL", CommandType.StoredProcedure, parms);

            if (!System.String.IsNullOrEmpty(parms[2].Value.ToString()))
            {
                return int.Parse(parms[2].Value.ToString());
            }
            return 0;
        }
        public int CheckJK_MES(string sfc_code, string jk_name, string barcode, int position, ref string containerbarcode)
        {
            int reworkcount;
            string sql = "select count(1),containerbarcode from jk_mes where  jk_name='" + jk_name + "' and containerbarcode ='" + barcode + "' limit 1";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    reworkcount = int.Parse(dt.Rows[0][0].ToString());
                    containerbarcode = dt.Rows[0][1].ToString();
                }
                else
                    return 0;
            }
            else
                return 0;
            return reworkcount;
        }
        public bool AddJK_CellInfo(string zoneid, string zonecode, string containerbarcode, string gongyi_id, string status, string jk_name, string tar_sys, string createuser, string ues_count, string mes_site, string operation_revision, string mes_resource, string sfc_code, string SFC_POSITION, string SFC_MODE,string i_operationtype, string mesuser,ref string id)
        {
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("i_warehouseid", MySqlDbType.VarChar, 32),
                new MySqlParameter("i_ZONEID", MySqlDbType.VarChar, 32),
                new MySqlParameter("i_containerbarcode", MySqlDbType.VarChar,20),
                new MySqlParameter("i_GONGYI_ID", MySqlDbType.VarChar,50),
                new MySqlParameter("i_JK_NAME", MySqlDbType.VarChar,50),
                new MySqlParameter("i_TAR_SYS", MySqlDbType.VarChar,50),
                new MySqlParameter("i_CREATEUSER", MySqlDbType.VarChar,50),
                new MySqlParameter("i_OPERATION_REVISION", MySqlDbType.VarChar,50),
                new MySqlParameter("i_mes_resource", MySqlDbType.VarChar,50),
                new MySqlParameter("i_SFC_CODE", MySqlDbType.VarChar,30),
                new MySqlParameter("i_SFC_POSITION", MySqlDbType.VarChar,20),
                new MySqlParameter("i_SFC_MODE", MySqlDbType.VarChar,20),
                new MySqlParameter("i_operationtype",MySqlDbType.VarChar,20),
                new MySqlParameter("i_parentlognoid", MySqlDbType.VarChar,50),
                new MySqlParameter("i_mesuser", MySqlDbType.VarChar,50),
                new MySqlParameter("o_result", MySqlDbType.Float),
                new MySqlParameter("o_Id", MySqlDbType.VarChar,32)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;

            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = zoneid;

            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = containerbarcode;

            parms[3].Direction = ParameterDirection.Input;
            parms[3].Value = gongyi_id;

            parms[4].Direction = ParameterDirection.Input;
            parms[4].Value = jk_name;

            parms[5].Direction = ParameterDirection.Input;
            parms[5].Value = tar_sys;
            parms[6].Direction = ParameterDirection.Input;
            parms[6].Value = createuser;

            parms[7].Direction = ParameterDirection.Input;
            parms[7].Value = operation_revision;

            parms[8].Direction = ParameterDirection.Input;
            parms[8].Value = mes_resource;

            parms[9].Direction = ParameterDirection.Input;
            parms[9].Value = sfc_code;

            parms[10].Direction = ParameterDirection.Input;
            parms[10].Value = SFC_POSITION;

            parms[11].Direction = ParameterDirection.Input;
            parms[11].Value = SFC_MODE;

            parms[12].Direction = ParameterDirection.Input;
            parms[12].Value = i_operationtype;

            parms[13].Direction = ParameterDirection.Input;
            parms[13].Value = "";

            parms[14].Direction = ParameterDirection.Input;
            parms[14].Value = mesuser;

            parms[15].Direction = ParameterDirection.Output;
            parms[15].Value = 0;

            parms[16].Direction = ParameterDirection.Output;
            parms[16].Value = "";

            int i = DataAccessFactory.Instance.ExecuteNonQuery("wcs_addjk_mes_p_atl", CommandType.StoredProcedure, parms);
            if (!System.String.IsNullOrEmpty(parms[15].Value.ToString()))
            {
                if (Int32.Parse(parms[15].Value.ToString())!=1)
                    return false;
                else
                {
                    id = parms[16].Value.ToString();
                    return true;
                }
            }
            else
            {
                return false;
            }
          
        }
        public bool checkCellIsSame(string palltecode,ref string itembarcode)
        {
            string sql = @"select itemcode from wcs_itemcode wi where  wi.barcode = '" + palltecode + "'and  SUBSTR(wi.itemcode, 1, 3) != 'WCS' AND wi.itemcode IS NOT NULL AND wi.itemcode != 'Empty' order by wi.sequenceno limit 1";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                itembarcode = null;
                return false;
            }
            else
            {
                itembarcode = ds.Tables[0].Rows[0][0].ToString();
                return true;
            }
        }
        public bool UpdateCellStatusOk(string palltecode)
        {
            string sql = "update wcs_itemcode set BINDRESULT='0',tobaccotype=null  where warehouseid = '" + WareHouseID + "' and barcode='" + palltecode + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }

        public bool UpdateCellStatus(string palltecode, int cellcount, string itemcode)
        {
            string sql = "update wcs_itemcode set itemcode='" + itemcode + "' where warehouseid = '" + WareHouseID + "' and barcode='" + palltecode + "' and sequenceno='" + cellcount + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql,null);
            if (i > 0)
                return true;
            return false;
        }

        public bool UpdateItembarcode(string palltecode,int itemposition,string itembarcode,string robotName)
        {
            string sql = "update itemdetail set itembarcode=CONCAT('WCS','" + itembarcode + "'),last_modified_by='" + robotName + "' where  containerbarcode='" + palltecode + "' " +
                "and  itembarcode='" + itembarcode + "'and itemposition='" + itemposition + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }
        public static bool checkItembarcode(string palltecode, int itemposition)
        {
            string sql = @"SELECT  * FROM itemdetail  WHERE containerbarcode= '" + palltecode + "'" +
                "and  itemposition = '" + itemposition + "' AND itembarcode LIKE 'WCS%'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool GetGongYi(string stationno, string zoneid, string gongyyi_name, string barcode, ref string mes_site, ref string operation_revision, ref string mes_resource, ref string mesuser,ref string gongyi_id)
        {
            string sql = " SELECT  mes_code, mes_site, operation_revision, mes_resource,mes_user from technology  t INNER JOIN equipment e ON t.technologyid=e.technologyid AND e.equipmentnumber='" + stationno + "' ";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    gongyi_id = dt.Rows[0][0].ToString();
                    mes_site = dt.Rows[0][1].ToString();
                    operation_revision = dt.Rows[0][2].ToString();
                    mes_resource = dt.Rows[0][3].ToString();
                    mesuser = dt.Rows[0][4].ToString();
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }
        public bool DeleteJK_NAME(string id)
        {
            if (string.IsNullOrEmpty(id))
                id = "EMPTY";
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("i_id", MySqlDbType.VarChar, 32),
                new MySqlParameter("o_result", MySqlDbType.Int32)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = id;

            parms[1].Direction = ParameterDirection.Output;
            parms[1].Value = 0;

            int i = DataAccessFactory.Instance.ExecuteNonQuery("WCS_MOVEJK_MES_P_ATL", CommandType.StoredProcedure, parms);
            if (!System.String.IsNullOrEmpty(parms[1].Value.ToString()))
            {
                if (parms[1].Value == null)
                    return false;
                else
                    return int.Parse(parms[1].Value.ToString()) > 0;
            }
            else
                return false;
        }

        public DataTable GetBatteryCodeByTrayCode(string palltecode)
        {
            string sql = "select  itemcode,sequenceno,bindresult,tobaccotype from wcs_itemcode where barcode='" + palltecode + "' and rownum<17 order by sequenceno";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null && ds.Tables.Count > 0)
                return ds.Tables[0];
            return null;
        }

        public string[] GetCellOKInfo(string pattlecode, int cellNum)
        {
            string[] ss = new string[cellNum * 2];
            string strSql = @"select case
                 when itembarcode LIKE 'WCS%'  then
                  '9'           
                   else
                    '1'
               end as countid,itembarcode              
          from itemdetail a
         where containerbarcode =trim('" + pattlecode + "') order by itemposition ASC";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(strSql, CommandType.Text, null);

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ss[i] = dt.Rows[i][0].ToString();
                        ss[i + dt.Rows.Count] = dt.Rows[i][1].ToString();
                    }
                }
                else
                    return null;
            }
            else
                return null;
            return ss;
        }

        public bool pickCellOKInfo(string pattlecode)
        {
            string sql = @"select count(1) from itemdetail i  where i.itembarcode NOT LIKE 'WCS%' and i.containerbarcode = trim('" + pattlecode + "')  and i.statusflag NOT IN('0')";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                return int.Parse(ds.Tables[0].Rows[0][0].ToString()) == 0 ? true : false;
            }
        }

        public string[] GetCellNGInfo(string pattlecode, int cellNum)
        {
            string[] ss = new string[cellNum * 2];
            string strSql = @"select case
                 when itembarcode LIKE 'WCS%'  then
                  '9'           
                   else
                    '1'
               end as countid,itembarcode              
          from itemdetail a
         where containerbarcode =trim('" + pattlecode + "') order by itemposition ASC";



            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(strSql, CommandType.Text, null);

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ss[i] = dt.Rows[i][0].ToString();
                        ss[i + dt.Rows.Count] = dt.Rows[i][1].ToString();
                    }
                }
                else
                    return null;
            }
            else
                return null;
            return ss;
        }

        public string[] GetCellNGInfoFR(string pattlecode, int cellNum,string operation)
        {
            //0，无  1代表OK、2代表NG，3代表化成/OCV2复测，4代表E99,5代表AG复测，6代表DG复测 ,7 OCV1/OCVB复测  9代表无
            // 需要配置mes_nclevel表,若表中没有配置该工艺,则认为0是正常 9是E99电芯 其它全为NG
            // 其中act_status值为0时表示该工序复测组盘后不需要解NC  1表示需要解NC
            //当operation与表中operation_ng不一致时  默认NG
            //MES开头 表示在MES中已解绑  默认NG
            //string[] ss = new string[cellNum * 2];
            //string strSql = @"select case
            //        WHEN itembarcode LIKE 'WCS%'  THEN
            //         '9'
            //       WHEN itembarcode LIKE 'MES%'  THEN
            //         '2'
            //        WHEN itembarcode NOT LIKE 'WCS%' and itembarcode NOT LIKE 'MES%' and  a.operation_ng is not null and  a.operation_ng!='' and a.operation_ng='{0}' THEN
            //          case
            //              WHEN (SELECT COUNT(1) FROM mes_nclevel M WHERE M.gongyi_id=a.operation_ng)>0 then
            //                  case  
            //                    when STATUSFLAG in('0') then '1' 
            //                    when STATUSFLAG in(SELECT M.nclevel FROM mes_nclevel M WHERE M.gongyi_id=a.operation_ng) THEN
            //                      (SELECT M.robotResult FROM mes_nclevel M WHERE M.gongyi_id=a.operation_ng and m.Nclevel=a.statusflag LIMIT 1)
            //                    when STATUSFLAG = '9' then '4' 
            //                    else
            //                     '2'
            //                  END         
            //              else
            //                   case  
            //                      when STATUSFLAG = '0' then '1' 
            //                      when STATUSFLAG = '9' then '4'           
            //                      ELSE '2'
            //                   end 
            //              end 
            //       ELSE 
            //        '2'
            //       end  as countid,itembarcode              
            // from itemdetail a
            // where containerbarcode =trim('{1}') order by itemposition ASC";
            //DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(string.Format(strSql,operation,pattlecode), CommandType.Text, null);

            //-------------------------------NCXWD--------------------------------------------
            //MES的状态    0表示OK，  1表示NG值超限需要复测，2表示通道锁定处理同1需要复测，3表示测试结果失败并判定NG不需要复测，4未反馈测试，需复测
            //机械手的状态 0，无  2、OCVNG  1 OK  3、OCV1复测,OCV2复测  4、DCR复测 5、DCRNG 9.没有电芯
            string[] ss = new string[cellNum * 2];
            string strSql = @"select case
                    WHEN itembarcode LIKE 'WCS%'  THEN '9'
                    WHEN itembarcode not LIKE 'WCS%' and STATUSFLAG = '0' THEN '1'
                    WHEN itembarcode not LIKE 'WCS%' and STATUSFLAG in('1') then
                        case 
                         when t.mes_code in ('CDCR01') OR t.mes_code_rework in ('CDCR01')  THEN '5'
                        else '2' end
                    WHEN itembarcode not LIKE 'WCS%' and STATUSFLAG IN('2','3','4') then
                        case 
                         when t.mes_code in ('CDCR01') OR t.mes_code_rework in ('CDCR01') THEN '4' 
                        else '3' end
                    ELSE
                     '2'
             end as countid,itembarcode
             from itemdetail a LEFT JOIN technology t ON a.version = t.technologyid
             where containerbarcode = trim('{0}') order by itemposition ASC";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(string.Format(strSql, pattlecode), CommandType.Text, null);

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        ss[i] = dt.Rows[i][0].ToString();
                        ss[i + dt.Rows.Count] = dt.Rows[i][1].ToString();
                    }
                }
                else
                    return null;
            }
            else
                return null;
            return ss;
        }

        public string getOperation(string pattlecode)
        {
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("i_containerbarcode", MySqlDbType.VarChar, 32),
                new MySqlParameter("o_operation", MySqlDbType.VarChar,20),
                new MySqlParameter("o_result", MySqlDbType.Int32)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = pattlecode;
            parms[1].Direction = ParameterDirection.Output;
            parms[1].Value = "";
            parms[2].Direction = ParameterDirection.Output;
            parms[2].Value = 0;

            int i = DataAccessFactory.Instance.ExecuteNonQuery("GetPreviousMES_code", CommandType.StoredProcedure, parms);
            if (!System.String.IsNullOrEmpty(parms[2].Value.ToString()))
            {
                if (parms[2].Value == null)
                    return null;
                else
                {
                    return parms[1].Value.ToString();
                }
            }
            else
                return null;
        }
        public string CheckExistsRelease(ref bool flag, ref string msg, string zoneid, string containerbarcode, string jk_name)
        {
            flag = false;
            msg = "";
            string sql = @"select distinct result from jk_mes where containerbarcode = '" + containerbarcode + "' and jk_name = '" + jk_name + "' ";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return "";
            }
            else
            {
                flag = true;
                string str = ds.Tables[0].Rows[0][0].ToString().Trim();
                return str;
            }
        }

        public int getitemcodenum(string barcode, string itemcode,int itemposition)
        {
            int num = 0;
            string sql = "select count(1) from wcs_itemcode   where barcode = '" + barcode + "'and itemcode = '" + itemcode + "' and sequenceno!='"+ itemposition + "'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null && ds.Tables.Count>0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    num = int.Parse(dt.Rows[0][0].ToString());
                     
                }
                else
                    return 0;
            }
            else
                return 0;
            return num;
        }

        public string CheckCondition(string stationno,string barcode)
        {
            string result = string.Empty;
            MySqlParameter[] parms = new MySqlParameter[]
            {
                new MySqlParameter("i_warehouseId", MySqlDbType.VarChar, 32),
                new MySqlParameter("i_station", MySqlDbType.VarChar, 20),
                 new MySqlParameter("i_barcode", MySqlDbType.VarChar, 20),
                new MySqlParameter("o_result", MySqlDbType.Int32),
                new MySqlParameter("o_checkresult",MySqlDbType.VarChar,1000)
            };
            parms[0].Direction = ParameterDirection.Input;
            parms[0].Value = WareHouseID;
            parms[1].Direction = ParameterDirection.Input;
            parms[1].Value = stationno;
            parms[2].Direction = ParameterDirection.Input;
            parms[2].Value = barcode;
            parms[3].Direction = ParameterDirection.Output;
            parms[3].Value = 0;
            parms[4].Direction = ParameterDirection.Output;
            parms[4].Value = "";

            int i = DataAccessFactory.Instance.ExecuteNonQuery("m_checkinboundcondition_p", CommandType.StoredProcedure, parms);
            result = parms[4].Value.ToString();
            return result;
        }
        #endregion
        public bool CheckUserInfo(string password,ref string username)//检测用户
        {
            string passwordstr = ClassDES.EncryptDES(password, "ntitotci");
            string sql = @"select username from lmep_system_user where userpswd='" + passwordstr + "' limit 1";

            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                 username= ds.Tables[0].Rows[0][0].ToString();
                return true;
            }
            return false;
        }

        public bool UpdateItempalletTostation(string palltecode,string tostation)
        {
            string sql = "update itempallet set tostation='"+ tostation + "' where containerbarcode='" + palltecode + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }
        public string GetItempalletTostation(string palltecode)
        {
            string sql = @"select tostation from itempallet i where  i.containerbarcode = '" + palltecode + "' limit 1";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return null;
            }
            else
            {
                return ds.Tables[0].Rows[0][0].ToString();
            }
        }
        public int getNeedBufferCount(string tostation)
        {
            string sql = @"select count(1) from wcs_subtaskinfo w where  w.tostation = '" + tostation + "'";
            string sql1 = @"select count(1),wc.CELLCOUNT  from wcs_cellcount wc where  wc.FINIASTATION = '" + tostation + "'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            int taskCount = int.Parse(ds.Tables[0].Rows[0][0].ToString());
            DataSet ds1 = DataAccessFactory.Instance.ExecuteDataSet(sql1, CommandType.Text, null);
            int cellCount = int.Parse(ds1.Tables[0].Rows[0][0].ToString()) > 0 ? int.Parse(ds1.Tables[0].Rows[0][1].ToString()) : 0;
            return (cellCount - taskCount) < 0 ? 0 : cellCount - taskCount;
        }
        public bool GetCellCount(string station)
        {
            string sql = @"select tostation from wcs_cellcount wc   WHERE wc.FINIASTATION='"+ station + "' AND (wc.CELLCOUNT-wc.CELLCOUNTEXCTING)>0";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public bool UpdateCellCount(string station, bool flag)
        {
            string sql = string.Empty;
            if (flag)
            {
                sql = "update wcs_cellcount set CELLCOUNTEXCTING=CELLCOUNTEXCTING+1 where FINIASTATION='" + station + "'";
            }
            else
                sql = "update wcs_cellcount set CELLCOUNTEXCTING= IF(CELLCOUNTEXCTING<=0,0,CELLCOUNTEXCTING-1) where FINIASTATION='" + station + "'";
            int i = DataAccessFactory.Instance.ExecuteNonQuery(CommandType.Text, sql, null);
            if (i > 0)
                return true;
            return false;
        }

        public static bool getExceptionTostation(string station,ref string exceptionstation)
        {
            string sql = @"SELECT  wc.exceptionstation FROM wcs_configure wc  WHERE wc.station= '" + station + "'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                exceptionstation= ds.Tables[0].Rows[0][0].ToString();
                return true;
            }
        }

        public string[] getItemcodeByPalltecode(string palltecode,string zonecode)
        {
            string[] itemcodes = new string[2];
            string sql1 = string.Empty;
            string sql2 = string.Empty;
            if (LineCode == "L7" || LineCode == "L8")
            {
                sql1 = @"select itemcode,i.sequenceno AS sort from wcs_itemcode i where  i.barcode  = '" + palltecode + "' and sequenceno in('1','32')" +
              " UNION" +
              " SELECT ITEMBARCODE,i.itemposition AS sort FROM itemdetail i WHERE i.containerbarcode = '" + palltecode + "' AND i.itemposition IN('1','32') " +
               "ORDER BY sort";
                sql2 = @"select itemcode,i.sequenceno AS sort from wcs_itemcode i where  i.barcode  = '" + palltecode + "' and sequenceno in('1','24')" +
                   " UNION" +
                   " SELECT ITEMBARCODE,i.itemposition AS sort FROM itemdetail i WHERE i.containerbarcode = '" + palltecode + "' AND i.itemposition IN('1','24') " +
                    "ORDER BY sort";
            }
            else
            {
                sql1 = @"select itemcode,i.sequenceno AS sort from wcs_itemcode i where  i.barcode  = '" + palltecode + "' and sequenceno in('17','16')" +
              " UNION" +
              " SELECT ITEMBARCODE,i.itemposition AS sort FROM itemdetail i WHERE i.containerbarcode = '" + palltecode + "' AND i.itemposition IN('17','16') " +
               "ORDER BY sort desc";
                sql2 = @"select itemcode,i.sequenceno AS sort from wcs_itemcode i where  i.barcode  = '" + palltecode + "' and sequenceno in('13','12')" +
                   " UNION" +
                   " SELECT ITEMBARCODE,i.itemposition AS sort FROM itemdetail i WHERE i.containerbarcode = '" + palltecode + "' AND i.itemposition IN('13','12') " +
                    "ORDER BY sort desc";
            }

            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(zonecode=="HC"?sql1: sql2, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                itemcodes[0] = "";
                itemcodes[1] = "";
                return itemcodes;
            }
            else
            {
                itemcodes[0]= ds.Tables[0].Rows[0][0].ToString();
                itemcodes[1] = ds.Tables[0].Rows[1][0].ToString();
                return itemcodes;
            }
        }

        public bool getItemCodes(string palltecode, ref Dictionary<int, string> itemcodes)
        {
            string sql = @"select itemcode as itembarcode,i.sequenceno AS sort from wcs_itemcode i where  i.barcode  = '" + palltecode + "'" +
              " UNION" +
              " SELECT ITEMBARCODE  as itembarcode ,i.itemposition AS sort FROM itemdetail i WHERE i.containerbarcode = '" + palltecode + "' " +
               "ORDER BY sort";

            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    itemcodes.Add(int.Parse(dr["sort"].ToString()), dr["itembarcode"].ToString());
                }
                return true;
            }
        }
        public bool getLocation(string locationnumber, string equipmentnumber)
        {
            string sql = @"SELECT  count(1) FROM location l  LEFT JOIN equipment e ON E.equipmentid=L.per_equipmentid WHERE l.locationnumber= '" + locationnumber + "' AND e.equipmentnumber='" + equipmentnumber + "'";
            DataSet ds = DataAccessFactory.Instance.ExecuteDataSet(sql, CommandType.Text, null);
            if (ds == null || ds.Tables[0].Rows.Count <= 0)
            {
                return false;
            }
            else
            {
                return int.Parse(ds.Tables[0].Rows[0][0].ToString()) > 0 ? true : false;
            }
        }

        public DataSet GetScanConfigure()
        {
            DataSet ds = null;
            ds = DataAccessFactory.Instance.ExecuteDataSet("SELECT ws.station,ws.ip,ws.port,ws.flag,ws.description FROM wcs_scanconfigure ws ", CommandType.Text, null);
            return ds;
        }
    }
}
